import * as THREE from "three"
import initRenderer from "./core/renderer";
import initScene from "./core/scene";

class Box {
    private scene;
    private camera;
    private renderer;
    private container;
    private time = 0;
    private num = 15;   //火焰的帧数
    private textures = [];

    constructor(container) {
        this.container = container;
        this.scene = new THREE.Scene();
        this.init();
    }
    init() {
        // 初始化渲染器和相机
        let { renderer, camera, render } = initRenderer({ scene: this.scene, container: this.container });
        this.renderer = renderer;
        this.camera = camera;
        this.renderer.setClearColor("black");

        // 初始化场景
        initScene({ scene: this.scene, container: this.container, renderer: this.renderer, camera: this.camera });

        //初始化模型
        this.initObjects();

        // 开始渲染
        render();
    }

    //绘制
    initObjects() {
        let flame1 = this.createFlame('/model/flame/火焰test.png');
        this.scene.add(flame1);

        let flame2 = this.createFlame('/model/flame/火焰.png');
        flame2.position.x = 100;
        this.scene.add(flame2);

        this.animate();
    }

    createFlame(modelPath) {
        var w = 60;//火焰宽度  通过参数w可以快速调节火焰大小，以便于适应对应的三维场景
        var h = 1.6 * w;//火焰高度
        const geometry = new (THREE as any).PlaneBufferGeometry(w, h); //矩形平面
        geometry.translate(0, h / 2, 0);//火焰底部中点和局部坐标系坐标原点重合

        var textureLoader = new THREE.TextureLoader();//纹理贴图加载器
        const texture = textureLoader.load(modelPath);//创建一个纹理对象
        texture.repeat.set(1 / this.num, 1);// 1/num：从图像上截图一帧火焰，可以理解成横纵向截取的百分比 (uv两个方向纹理重复数量)
        // texture.offset.x = 0 / this.num;//选择第1帧火焰
        // texture.offset.x = 1 / this.num;//选择第2帧火焰
        // texture.offset.x = (this.num-1) / this.num;//选择第一帧火焰
        var material = new THREE.MeshBasicMaterial({
            map: texture,
            transparent: true,
            side: THREE.DoubleSide, //双面可见
        });
        var flame = new THREE.Mesh(geometry, material);// 火焰网格模型
        this.textures.push(texture);
        return flame;
    }

    animate() {
        this.time += 0.1;//调节火焰切换速度
        if (this.time > this.num) this.time = 0;
        //  Math.floor(t)取整 保证一帧一帧切换
        this.textures.forEach(tt => {
            tt.offset.x = Math.floor(this.time) / this.num;// 动态更新纹理偏移 播放关键帧动画 产生火焰然后效果
        });
        requestAnimationFrame(this.animate.bind(this));
    }
}

export default Box;